
from fisher import twoTailedPValue
import sys


if __name__=="__main__":
    file = sys.argv[1]
    cutoff = float(sys.argv[2])
    bases = ["A", "C", "G", "T"]
    print >> sys.stderr, "# Checking for p-value < %f in %s" % (cutoff, file)
    n = 0
    passed = 0
    for line in open(file):
        cols = line.strip().split("\t")
        if len(cols)<11:
            continue
        oldbase = cols[1]
        newbase = cols[2]
        n += 1
        tot1 = tot2 = 0
        snp1 = snp2 = 0
        for ix in xrange(4):
            tot1 += int(cols[3+ix])
            tot2 += int(cols[7+ix])
            if bases[ix]==newbase:
                snp1 += int(cols[3+ix])
                snp2 += int(cols[7+ix])
        pval = twoTailedPValue(snp1, tot1-snp1, snp2, tot2-snp2)
        if pval<=cutoff:
            passed += 1
            print "%s\t%f\t%f" % (line.strip(), pval, abs(1.0*snp1/tot1 - 1.0*snp2/tot2))
    print >> sys.stderr, "# Found %d passing cutoff, out of %ld candidates (ratio = %.8f = cutoff * %.8f)" % (passed, n, 1.0*passed/n, 1.0*passed/n/cutoff)

